package com.ddd.demo.lee.二分;

public class 二分查找 {

    public static void main(String[] args) {

        int[] arr = new int[]{1, 2, 3, 4, 5, 6, 7, 8};

        int result = binarySearch(arr, 8);

        System.out.println("result = " + result);
    }

    private static int binarySearch(int[] arr, int i) {
        int result = -1;
        int left = 0;
        int right = arr.length - 1;

        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (arr[mid] > i) {
                right = mid - 1;
            } else if (arr[mid] < i) {
                left = mid + 1;
            } else {
                return mid;
            }
        }
        return result;
    }

}
